const order = require("../model/orderModel");
const getDateTime = require("../utils/getDateTime");

/**
 * 获取总交易额
 * @returns Promise
 */
exports.orderTotalPrice = async () => {
  return await order.aggregate([
    {$match:{ isDelete:0 }},
    { $group: { _id: null, totalPrice: { $sum: "$tradeMoney" } } },
  ]);
};

exports.getOrderCount = async () => {
  return await order.find({isDelete:0}).count();
}

/**
 * 根据传递的时间戳范围找出 今天 或 上个星期 或 上个月的订单总额
 */
exports.cycleTradePrice = async (cycleType) => {
  const [startTime, endTime] = getDateTime(cycleType);
  if (startTime === 0 && endTime === 0) {
    return undefined;
  } else {
    return await order.aggregate([
      { $match: { tradeCreateDate: { $gte: startTime, $lte: endTime },isDelete:0 } },
      { $group: { _id: null, cycleTradePrice: { $sum: "$tradeMoney" } } },
    ]);
  }
};

/**
 * @param {String} searchContent 
 * @param {Number} pageIndex 
 * @param {Number} pageSize 
 * @returns 
 */
exports.getOrders = async (searchContent,pageIndex = 1,pageSize = 12) => {
  const f = searchContent ? {orderNo:{$regex:new RegExp(searchContent)},isDelete:0}  : {isDelete:0};
  return await order
    .find(f)
    .skip((pageIndex - 1) * pageSize)
    .limit(pageSize)
    .sort({
      tradeCreateDate:-1
    });
}

/**
 * 根据ID删除一个订单
 * @param {String} _id 
 * @returns 
 */
 exports.deleteOrderById = async (_id) => {
  return await order.updateOne({_id},{isDelete:1})
}

/**
 * 根据一个订单号 查询订单信息
 * @param {String} orderNo 
 * @returns 
 */
exports.findOrderByOrderNo = async (orderNo) => {
  return await order.find({orderNo,isDelete:0})
}


/**
 * 增加一个学生
 * @param {Order} order
 * @returns 
 */
 exports.addOrder = async (ord) => {
  return new order({
    ...ord
  }).save();
}


/**
 * 修改订单状态
 * @param {String} orderNo 
 * @param {Number} status {0|1|2}
 * @returns 
 */
exports.updateOrderStatus = async (orderNo,status) => {
  return await order.updateOne({orderNo,isDelete:0},{tradePayStatus:status})
}

